import db from '../../utils/dbconf';
import makeres from '../../utils/res';
import { TargetDataNoneError } from '../../utils/classModal';

import { TABLE_NAME as CARD_TABLE } from './cardcrud';
import { TABLE_NAME as GROUP_TABLE } from './groupcrud';
export const TABLE_NAME = 'RELACTIVE_MJ_GROUP_CARD';

//* 暂时不开启
const check_bolong = async ({ u_id, group_id, card_id }) => {
	if (u_id && group_id) {
		const e = await db.table(GROUP_TABLE).where({ u_id, id: group_id }).find();
		if (!e) throw new Error('牌组归属异常');
	}
	if (u_id && card_id) {
		const e = await db.table(CARD_TABLE).where({ u_id, id: card_id }).find();
		if (!e) throw new Error('牌型归属异常');
	}
};

export const relactionTool = {
	add: async ({ body: { ids, group_id } }, res) => {
		const { u_id } = res.locals;
		const data = ids.map((card_id, i) => ({ card_id, group_id, weight: i }));
		await db.table(TABLE_NAME).where({ group_id }).delete();
		const resdata = await db.table(TABLE_NAME).addAll(data);
		return res.send(makeres.success(resdata));
	},
	batchadd: async ({ body: data }, res) => {
		return res.send(makeres.success({ ids }));
	},
	delete: async ({ query: { card_id, group_id } }, res) => {
		const { u_id } = res.locals;
		const ok = await db.table(TABLE_NAME).where({ card_id, group_id }).delete();
		if (!ok) throw new TargetDataNoneError();
		return res.send(makeres.deletesuccess());
	},
	clear: async ({ params: { group_id } }, res) => {
		const { u_id } = res.locals;
		const ok = await db.table(TABLE_NAME).where({ group_id }).delete();
		if (!ok) throw new TargetDataNoneError();
		return res.send(makeres.deletesuccess());
	},
	setweight: () => {},
	getbygroup: async (group_id) => {
		const resdata = await db
			.table(TABLE_NAME)
			.where({ group_id })
			.field('card_id,u_id,name')
			.join({
				table: CARD_TABLE,
				join: 'left',
				on: ['card_id', 'id'],
			})
			.select();
		return resdata;
	},
	getbycard: async (card_id) => {
		const resdata = await db
			.table(TABLE_NAME)
			.where({ card_id })
			.field('group_id,u_id,name')
			.join({
				table: GROUP_TABLE,
				join: 'left',
				on: ['group_id', 'id'],
			})
			.select();
		return resdata;
	},
};
